<template>
    <div>
        <a-collapse accordion v-show="visible" class="collapse">
            <a-collapse-panel key="1" header="规则描述">
                <a-collapse :activeKey="activeKey" @change="handleChange">
                    <a-collapse-panel
                        :key="k"
                        :header="v.title"
                        v-for="(v, k) in ruleList"
                        @click.self="clickCollapsePanel(k)"
                    >
                        <a-tag
                            v-for="(rv, rk) in v.rules"
                            :key="rk"
                            style="margin: 5px"
                            :closable="k == collapseKey && allowEdit"
                            @close="delTag(k, rk)"
                            v-model="rv.visible"
                        >
                            {{ rv.text }}
                        </a-tag>
                        <a-icon slot="extra" type="edit" @click.stop="editRule(k)" style="margin-right: 15px;" />
                        <a-icon slot="extra" type="delete" @click="delRule(k)" />
                        <a-row type="flex" justify="end" v-show="allowEdit">
                            <a-button style="margin-right: 5px;" @click="cancelDelRule(k)">
                                放弃
                            </a-button>
                            <a-button type="primary" @click="saveDelRule(k)">
                                保存
                            </a-button>
                        </a-row>
                    </a-collapse-panel>
                </a-collapse>
            </a-collapse-panel>
            <a-collapse-panel key="2" header="新增规则">
                <a-form
                    :form="form"
                    :label-col="{ span: 5 }"
                    :wrapper-col="{ span: 12 }"
                    @submit="addCustRules"
                    style="width: 100%"
                >
                    <a-form-item label="规则名称">
                        <a-input v-decorator="['title', { rules: [{ required: true, message: '请输入规则名称' }] }]" />
                    </a-form-item>
                    <a-form-item label="规则描述">
                        <a-input v-decorator="['desc', { rules: [{ message: '请输入规则描述' }] }]" />
                    </a-form-item>
                    <a-form-item label="过滤字段">
                        <div class="filter-text">
                            <a-input v-decorator="['ruleTag']" />
                            <a-button @click="addTag">添加</a-button>
                        </div>
                    </a-form-item>
                    <a-form-item>
                        <a-tag closable @close="closeTag(k)" v-for="(v, k) in tags" :key="k">
                            {{ v }}
                        </a-tag>
                    </a-form-item>
                    <a-divider style="margin: 12px 0px" />
                    <a-row type="flex">
                        <a-col>
                            <a-button html-type="submit" style="margin-right: 10px">
                                新增规则
                            </a-button>
                        </a-col>
                        <a-col><a-button @click="clearCustRules">清空规则</a-button></a-col>
                    </a-row>
                </a-form>
            </a-collapse-panel>
        </a-collapse>
        <a-row type="flex" justify="end" align="middle" style="margin-top: 15px;">
            <a-col><a-button @click="delConfig">删除配置文件</a-button></a-col>
        </a-row>
    </div>
</template>
<script>
    import { writeData, delFile } from '@/util/file-action'
    export default {
        name: 'RuleInfo',
        props: {
            visible: {
                type: Boolean,
                default: false,
            },
        },
        data() {
            return {
                ruleList: [],
                newRule: {},
                tags: [],
                collapseKey: 0, // 当前选中的collapse的key
                allowEdit: false,
                activeKey: [], // 当前展开的collapse集合
                delTagKeys: {},
                form: this.$form.createForm(this, { name: 'setCustRules' }),
            }
        },
        watch: {
            visible: {
                handler(nval) {
                    if (nval) {
                        const { ruleList } = this.$store.state.rules
                        let _ruleList = []
                        for (const list of ruleList) {
                            let rules = []
                            for (const v of list.rules) {
                                rules.push({
                                    text: v,
                                    visible: true,
                                })
                            }
                            _ruleList.push({
                                ...list,
                                rules,
                            })
                        }
                        for (const i in _ruleList) {
                            this.$set(this.ruleList, i, _ruleList[i])
                        }
                    }
                },
                deep: true,
            },
        },
        methods: {
            addCustRules(e) {
                e.preventDefault()
                const { tags, newRule } = this
                this.form.validateFields((err, values) => {
                    if (!err) {
                        if (tags.length > 0) {
                            const { description, title } = values
                            const newRule = {
                                id: 'rule' + Date.now().toString(36),
                                description: description ?? '',
                                title,
                                rules: this.tags,
                            }
                            writeData([newRule], 'ruleList', 'rule')
                            this.form.setFieldsValue({ title: '' })
                            this.tags = []
                        } else {
                            this.$message.error('过滤字段为空')
                        }
                    }
                })
            },
            delTag(k, rk) {
                if (!this.delTagKeys[k]) {
                    this.delTagKeys[k] = [rk]
                } else {
                    this.delTagKeys[k].push(rk)
                }
                const list = this.ruleList[k]
                list.rules[rk].visible = false
                this.$set(this.ruleList, k, list)
            },
            cancelDelRule(k) {
                const list = this.ruleList[k]
                for (const rk of this.delTagKeys[k]) {
                    list.rules[rk].visible = true
                    this.$set(this.ruleList, k, list)
                }
                delete this.delTagKeys[k]
            },
            saveDelRule(k) {
                const { ruleList, delTagKeys } = this
                const { rules } = ruleList[k]
                for (const v of delTagKeys[k]) {
                    rules.splice(v, 1)
                }
                this.$set(this.ruleList, k, { ...ruleList[k], rules })
                delete this.delTagKeys[k]
                this.allowEdit = false
            },
            clickCollapsePanel(k) {
                console.log('clickCollapsePanel: ', k)
                const i = this.activeKey.findIndex((v) => v == k)
                i != -1 ? this.activeKey.splice(i, 1) : this.activeKey.push(k.toString())
            },
            clearCustRules() {},
            addTag() {
                const ruleTag = this.form.getFieldValue('ruleTag')
                if (ruleTag) {
                    this.form.setFieldsValue({ ruleTag: '' })
                    this.tags.push(ruleTag)
                }
            },
            closeTag(k) {
                this.tags.splice(k, 1)
            },
            editRule(k) {
                this.collapseKey = k
                this.allowEdit = !this.allowEdit
                // 如果没展开就展开
                if (this.activeKey.findIndex((v) => v == k) == -1) {
                    this.activeKey.push(k.toString())
                }
            },
            delRule(k) {
                let { ruleList } = this
                ruleList.splice(k, 1)
                if (writeData(ruleList, 'ruleList', 'rule', true)) {
                    this.$store.commit('rules/setRuleList', ruleList)
                    for (const i in ruleList) {
                        this.$set(this.ruleList, i, ruleList[i])
                    }
                }
            },
            handleChange(k) {
                console.log('handleChange: ', k)
            },
            delConfig() {
                if (delFile('rule')) {
                    this.$message.success('删除成功')
                } else {
                    this.$message.error('删除失败')
                }
            },
        },
    }
</script>
<style lang="less" scoped>
    .collapse {
        user-select: none;
        /deep/ .ant-tag {
            font-size: 15px;
            padding: 5px 10px;
        }
        .filter-text {
            display: flex;
            input {
                margin-right: 5px;
            }
        }
        /deep/ .ant-form-item {
            margin: 0px;
            display: flex;
            justify-content: center;
        }
        /deep/ .ant-row-flex {
            display: flex;
            justify-content: flex-end;
        }
    }
</style>
